
//
//  CoerceEndOrderViewController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/8/27.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation
class CoerceEndOrderViewController: UIViewController {
    
    var orderId: String?                //当前订单id
    var imagePath = [String]()          //上传完成以后的图片地址数组
    var images = [UIImage]()            //选择上的图片数组
    var isEdit: Bool = false            //标记是否是编辑
    var index: Int = 9000                      //标记当前点击的是第几个
    
    @IBOutlet weak var describeTextField: UITextView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var height: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        collectionView.dataSource = self
        self.images.append(UIImage(named: "GroupCarmre")!)
    }
        
    func reloadTable() {
        
        let beishu = images.count / 2
        let shuyu = images.count % 2
        height.constant = shuyu == 0 ? CGFloat(beishu) * 99 : (CGFloat(beishu) + 1) * 99
        collectionView.reloadData()
    }
    
    //TODO:提交强制内容
    @IBAction func commitButton(_ sender: Any) {
        
        guard let text = describeTextField.text, text.count > 0 else {
            XHProgressHUD.showError("请输入你所遇到的问题")
            return
        }
        
        guard images.count > 1 else {
            XHProgressHUD.showError("请上传相关照片")
            return
        }
        
        guard let order = self.orderId else {
            showError("订单号错误")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.coerceEndOrder(orderId: order, descInfo: text, imagePath: imagePath, lat: userLocation?.latitude, lon: userLocation?.longitude, boardImage: nil, success: { [weak self] in
            JZLoading.hideLoading()
            self?.showError("结单成功")
            self?.navigationController?.popViewController(animated: true)
        }) { [weak self] message in
            JZLoading.hideLoading()
            self?.showError(message)
        }
    }
}

extension CoerceEndOrderViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        tipLabel.isHidden = textView.text.count > 0
    }
}

extension CoerceEndOrderViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        if let cell = cell as? CoerceCollectionCell {
            cell.imageView.image = images[indexPath.row]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count == 6 ? images.count - 1 : images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if images.count == 6 && indexPath.row == images.count - 1 {
            XHProgressHUD.showError("最多上传五张图片")
            return
        }
        //标记
        index = indexPath.row
        isEdit = indexPath.row != images.count - 1
        
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            
            present(cameraPicker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
    }
}

extension CoerceEndOrderViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
        
        User.uploadFile(image) { [weak self] path in
            if let self = self {
                if self.isEdit {
                    //替换
                    self.imagePath[self.index] = path
                    self.images[self.index] = image
                } else {
                    //新增
                    self.imagePath.append(path)
                    self.images.insert(image, at: self.images.count - 1)
                }
                //刷新
                self.reloadTable()
            }
        }
        
        dismiss(animated: true, completion: nil)
    }
}

